package com.fy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.common.config.AppConfig;
import com.fy.common.constants.MessageConstant;
import com.fy.ex.ConditionException;
import com.fy.ex.handler.ExceptionHandler;
import com.fy.mapper.EmailMapper;
import com.fy.mapper.FileInfoMapper;
import com.fy.mapper.FileShareMapper;
import com.fy.mapper.UserMapper;
import com.fy.pojo.dto.file.DownLoadCodeDTO;
import com.fy.pojo.dto.file.FileQueryDTO;
import com.fy.pojo.dto.file.RenameFileDTO;
import com.fy.pojo.dto.file.UploadFileDTO;
import com.fy.pojo.entity.FileInfo;
import com.fy.pojo.entity.FileShare;
import com.fy.pojo.entity.User;
import com.fy.pojo.enums.*;
import com.fy.pojo.vo.file.FileStatisticsVO;
import com.fy.pojo.vo.file.FoloderVO;
import com.fy.pojo.vo.file.PageResultData;
import com.fy.pojo.vo.user.LoginUserVO;
import com.fy.pojo.vo.user.UserSpaceVO;
import com.fy.service.FileInfoService;
import com.fy.utils.DateFormatter;
import com.fy.utils.RedisUtils;
import com.fy.utils.StringTools;
import com.fy.utils.aliyunUtils.AliOssFileOperation;
import com.fy.utils.fileUtils.FileUploadTool;
import com.fy.utils.result.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements FileInfoService {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private EmailMapper emailMapper;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Autowired
    private FileUploadTool fileUploadTool;

    @Autowired
    private FileShareMapper fileShareMapper;

    @Autowired
    private AliOssFileOperation aliOssFileOperation;

    /**
     * 定期检查数据库文件回收站情况并执行永久删除操作
     */
    @Override
    @Scheduled(fixedRate = 60000 * 24 * 10) // 每天执行一次
    @Transactional(rollbackFor = Exception.class)
    public void schedulDelRecoverFile() {
        try {
            log.info("开始执行回收站文件清理任务");

            // 1. 获取所有在回收站超过10天的文件和文件夹
            LambdaQueryWrapper<FileInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FileInfo::getDelFlag, FileDelFlagEnums.RECYCLE.getFlag())
                    .isNotNull(FileInfo::getRecoveryTime)
                    .lt(FileInfo::getRecoveryTime, new Date(System.currentTimeMillis() - 10 * 24 * 60 * 60 * 1000L)); // 超过10天

            List<FileInfo> recycleFiles = fileInfoMapper.selectList(wrapper);
            if (recycleFiles.isEmpty()) {
                log.info("没有需要清理的文件");
                return;
            }

            // 用于记录每个用户需要减少的空间
            Map<Integer, Long> userSpaceReduceMap = new HashMap<>();

            // 2. 处理文件和文件夹
            for (FileInfo fileInfo : recycleFiles) {
                if (FileFolderTypeEnums.FOLDER.getType().equals(fileInfo.getFolderType())) {
                    // 处理文件夹
                    processRecycleFolder(fileInfo, userSpaceReduceMap);
                } else {
                    // 处理文件
                    processRecycleFile(fileInfo, userSpaceReduceMap);
                }
            }

            // 3. 批量更新用户空间
            for (Map.Entry<Integer, Long> entry : userSpaceReduceMap.entrySet()) {
                Integer userId = entry.getKey();
                Long reduceSpace = entry.getValue();

                User user = userMapper.selectById(userId);
                if (user != null) {
                    long newSpace = Math.max(0, user.getUseSpace() - reduceSpace);
                    user.setUseSpace(newSpace);
                    userMapper.updateById(user);
                    log.info("更新用户[{}]空间使用量，减少：{}", userId, reduceSpace);
                }
            }

            log.info("回收站文件清理任务执行完成");
        } catch (Exception e) {
            log.error("回收站文件清理任务执行失败", e);
            throw e;
        }
    }

    /**
     * 处理回收站中的文件夹
     */
    private void processRecycleFolder(FileInfo folder, Map<Integer, Long> userSpaceReduceMap) {
        // 1. 获取文件夹下所有内容
        LambdaQueryWrapper<FileInfo> subWrapper = new LambdaQueryWrapper<>();
        subWrapper.eq(FileInfo::getFilePid, folder.getFileId());

        List<FileInfo> subFiles = fileInfoMapper.selectList(subWrapper);

        // 2. 递归处理子内容
        for (FileInfo subFile : subFiles) {
            if (FileFolderTypeEnums.FOLDER.getType().equals(subFile.getFolderType())) {
                processRecycleFolder(subFile, userSpaceReduceMap);
            } else {
                processRecycleFile(subFile, userSpaceReduceMap);
            }
        }

        // 3. 更新文件夹状态
        folder.setDelType(FileDelFlagEnums.DEL.getFlag());
        folder.setLastUpdateTime(new Date());
        fileInfoMapper.updateById(folder);
    }

    /**
     * 处理回收站中的文件
     */
    private void processRecycleFile(FileInfo file, Map<Integer, Long> userSpaceReduceMap) {
        // 1. 检查是否有其他用户在使用此文件
        LambdaQueryWrapper<FileInfo> wrapper = new LambdaQueryWrapper<>();

        // 查询条件
        wrapper.eq(FileInfo::getFileMd5, file.getFileMd5())
                .ne(FileInfo::getFileId, file.getFileId())
                .and(w -> w.eq(FileInfo::getDelType, FileDelFlagEnums.USING.getFlag())
                        .or()
                        .eq(FileInfo::getFileType, FileDelFlagEnums.RECYCLE.getFlag()));

        long otherUsersCount = fileInfoMapper.selectCount(wrapper);

        // 2. 更新文件状态为删除
        file.setDelType(FileDelTypeEnums.DEL_RECYCLE.getFlag());
        file.setLastUpdateTime(new Date());
        file.setDelFlag(FileDelFlagEnums.DEL.getFlag());
        fileInfoMapper.updateById(file);

        // 3. 如果没有其他用户使用，删除阿里云文件
        if (otherUsersCount == 0 && file.getFileObjectName() != null) {
            try {
                aliOssFileOperation.deleteFile(file.getFileObjectName());
                log.info("删除阿里云文件：{}", file.getFileObjectName());
            } catch (Exception e) {
                log.error("删除阿里云文件失败: {}", file.getFileObjectName(), e);
            }
        }

        // 4. 累加用户需要减少的空间
        userSpaceReduceMap.merge(file.getUserId(), file.getFileSize(), Long::sum);
    }

    /**
     * 上传文件
     *
     * @param loginUserVO
     * @param uploadFileDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadFile(LoginUserVO loginUserVO, UploadFileDTO uploadFileDTO) throws IOException {
        try {
            log.info("uploadFileDTO:{}",uploadFileDTO);
            MultipartFile multipartFile = uploadFileDTO.getFile();
            String fileName = uploadFileDTO.getFileName();
            Long fileSize=uploadFileDTO.getFileSize();

            // 2. 获取用户信息
            String nickName = loginUserVO.getNickName();
            int userId = Math.toIntExact(loginUserVO.getId());
            String userEmail=loginUserVO.getUserId();
            User user = userMapper.selectById(userId);

            ExceptionHandler.throwIf(user == null, "用户不存在");

            // 5. 检查文件MD5，实现秒传
            String fileMd5 = uploadFileDTO.getFileMd5();
            LambdaQueryWrapper<FileInfo> mdQuery = new LambdaQueryWrapper<>();
            mdQuery.eq(FileInfo::getFileMd5, fileMd5)
                    .eq(FileInfo::getDelType, FileDelTypeEnums.USING.getFlag())
                    .eq(FileInfo::getDelFlag, FileDelFlagEnums.USING.getFlag())
                    .eq(FileInfo::getFolderType, FileFolderTypeEnums.FILE.getType());
            List<FileInfo> existFiles = fileInfoMapper.selectList(mdQuery);

            if (!existFiles.isEmpty()) {
                // 实现秒传
                return handleQuickUpload(existFiles, userId, uploadFileDTO, fileName, userEmail);
            }


            // 3. 分片上传参数处理
            int chunkIndex = Integer.parseInt(uploadFileDTO.getChunkIndex());
            int chunks = Integer.parseInt(uploadFileDTO.getChunks());
            long chunkFileSize = multipartFile.getSize();

            // 4. 首片时检查空间
            if (chunkIndex == 0) {
                UserSpaceVO userSpaceVO = userMapper.selectSpaceByUserName(nickName);
                long totalFileSize = chunkFileSize * chunks;
                long unUseSpace = userSpaceVO.getTotalSpace() - userSpaceVO.getUseSpace();
                ExceptionHandler.throwIf(unUseSpace < totalFileSize, MessageConstant.INSUFFICIENT_SPACE);
            }

            // 6. 生成新文件信息
            String fileExtension = getFileExtension(fileName);
            String newFileName = generateFileName(loginUserVO.getUserId(), fileExtension);
            String newFileId = generateFileId(loginUserVO.getUserId());

            // 7. 处理文件上传
            List<String> uploadResult = fileUploadTool.uploadAndMerge(
                    multipartFile.getBytes(),
                    fileName,
                    chunkIndex,
                    chunks,
                    uploadFileDTO.getFileId(),
                    newFileName);

            ExceptionHandler.throwIf(uploadResult.isEmpty(),"文件上传失败");

            if (uploadResult.get(0) != null && uploadResult.get(1) == null) {
                return uploadResult.get(0);
            } else {
                // 8. 保存文件信息
                FileInfo fileInfo = new FileInfo();
                fileInfo.setFileId(newFileId);
                fileInfo.setUserId(userId);
                fileInfo.setFileName(fileName);
                fileInfo.setFilePid(uploadFileDTO.getFilePid());
                fileInfo.setFileSize(fileSize);
                fileInfo.setFileMd5(fileMd5);
                fileInfo.setFileType(FileTypeEnums.getFileTypeBySuffix(fileExtension).getType());
                fileInfo.setFolderType(FileFolderTypeEnums.FILE.getType());
                fileInfo.setDelType(FileDelFlagEnums.USING.getFlag());
                fileInfo.setStatus(FileStatusEnums.USING.getStatus());
                fileInfo.setDelFlag(FileDelFlagEnums.USING.getFlag());
                fileInfo.setCreateTime(new Date());
                fileInfo.setLastUpdateTime(new Date());

                // 判断是否为视频文件并获取封面
                if (ArrayUtils.contains(FileTypeEnums.VIDEO.getSuffixs(), fileExtension.toLowerCase())) {

                    // 获取视频封面 - 使用阿里云OSS视频截帧处理
                    // 在原视频URL后面拼接处理参数
                    // x-oss-process=video/snapshot,t_1000,f_jpg,w_800,h_600,m_fast
                    // t_1000: 截取视频第1秒的帧
                    // f_jpg: 输出jpg格式图片
                    // w_800,h_600: 设置输出图片的宽高
                    // m_fast: 采用快速截帧模式
                    String videoUrl = uploadResult.get(1);
                    String coverUrl = videoUrl + "?x-oss-process=video/snapshot,t_1000,f_jpg,w_800,h_600,m_fast";

                    // 设置文件封面
                    fileInfo.setFileCover(coverUrl);
                    log.info("视频文件封面获取成功: {}", coverUrl);

                }else if(ArrayUtils.contains(FileTypeEnums.IMAGE.getSuffixs(), fileExtension.toLowerCase())){
                    fileInfo.setFileCover(uploadResult.get(1));
                }else {
                    fileInfo.setFileCover(" ");
                }
                fileInfo.setFilePath(uploadResult.get(1));
                fileInfo.setFileObjectName(newFileName);
                fileInfo.setFileCategory(FileTypeEnums.getFileTypeBySuffix(fileExtension).getType());

                fileInfoMapper.insert(fileInfo);

                // 9. 更新用户空间
                updateUserSpace(userId, fileSize);

                return uploadResult.get(0);
            }
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw e;
        }
    }

    /**
     * 处理秒传逻辑
     */
    private String handleQuickUpload(List<FileInfo> existFiles, int userId, UploadFileDTO uploadFileDTO,
                                     String fileName, String nickName) {
        // 检查当前用户是否已有该文件
        for (FileInfo existFile : existFiles) {
            int uid=existFile.getUserId();
            ExceptionHandler.throwIf(uid==userId,"文件已存在，请勿重复上传");
        }

        // 创建新的文件记录，复用存储信息
        FileInfo newFile = new FileInfo();
        BeanUtils.copyProperties(existFiles.get(0), newFile);
        newFile.setFileId(generateFileId(nickName));
        newFile.setUserId(userId);
        newFile.setFileName(fileName);
        newFile.setFilePid(uploadFileDTO.getFilePid());
        newFile.setCreateTime(new Date());
        newFile.setLastUpdateTime(new Date());

        fileInfoMapper.insert(newFile);

        // 更新用户空间
        updateUserSpace(userId,newFile.getFileSize());

        return null;
    }

    /**
     * 更新用户空间使用量
     */
    private void updateUserSpace(int userId, long fileSize) {
        User user = userMapper.selectById(userId);
        long newUseSpace = user.getUseSpace() + fileSize;
        userMapper.updateSpaceByUserId(userId, newUseSpace);
    }

    /**
     * 生成文件名
     */
    private String generateFileName(String userEmail, String extension) {
        String prefix = StringTools.getEmailPrefix(userEmail);
        return prefix + "ADD" + UUID.randomUUID().toString().substring(0, 6) + extension;
    }

    /**
     * 生成文件ID
     */
    private String generateFileId(String userEmail) {
        String prefix = StringTools.getEmailPrefix(userEmail);
        return prefix + "ADD" + UUID.randomUUID().toString().substring(0, 6);
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf(".");
        return dotIndex > 0 ? fileName.substring(dotIndex) : "";
    }

    /**
     * 文件分页查询
     *
     * @param fileQueryDTO
     * @return
     */
    @Override
    public PageResult filePageQuery(FileQueryDTO fileQueryDTO, LoginUserVO loginUserVO) {
        // 1. 处理分页参数
        long pageSize = fileQueryDTO.getPageSize() != null && !fileQueryDTO.getPageSize().isEmpty()
                ? Long.parseLong(fileQueryDTO.getPageSize())
                : 15L; // 默认为1页15条数据
        long pageNo = fileQueryDTO.getPageNo() != null && !fileQueryDTO.getPageNo().isEmpty()
                ? Long.parseLong(fileQueryDTO.getPageNo())
                : 1L;// 默认为第一页

        String filePid = fileQueryDTO.getFilePid();
        if (filePid == null || filePid.isEmpty()) {
            filePid = "0"; // 默认查询根目录
        }

        String category = fileQueryDTO.getCategory();
        String fileNameFuzzy = fileQueryDTO.getFileNameFuzzy();

        // 2. 创建分页对象
        IPage<FileInfo> page = new Page<>(pageNo, pageSize);

        // 3. 构建查询条件
        LambdaQueryWrapper<FileInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileInfo::getDelType, FileDelFlagEnums.USING.getFlag())
                .eq(FileInfo::getUserId, userMapper.selectUserIdByName(loginUserVO.getNickName()));

        // 4. 添加分类查询条件
        if (StringUtils.isNotBlank(category)) {
            queryWrapper.eq(FileInfo::getFileCategory, FileCategoryEnums.getCategory(category));
        }

        // 5. 添加文件名模糊查询
        if (StringUtils.isNotBlank(fileNameFuzzy)) {
            queryWrapper.like(FileInfo::getFileName, fileNameFuzzy.toLowerCase());
        }

        // 6. 添加父目录查询条件
        queryWrapper.eq(FileInfo::getFilePid, filePid);

        // 8. 执行查询
        fileInfoMapper.selectPage(page, queryWrapper);

        // 9. 转换查询结果
        List<PageResultData> resultList = page.getRecords().stream()
                .map(record -> {
                    PageResultData pageResultData = new PageResultData();
                    BeanUtils.copyProperties(record, pageResultData);

                    if (record.getLastUpdateTime() != null) {
                        pageResultData.setLastUpdateTime(DateFormatter.getYMDhmsFormatterStringByCST(
                                String.valueOf(record.getLastUpdateTime())));
                    }

                    return pageResultData;
                })
                .collect(Collectors.toList());

        // 10. 构建返回结果
        PageResult pageResult = new PageResult();
        pageResult.setTotalCount(page.getTotal());
        pageResult.setPageNo(page.getCurrent());
        pageResult.setPageSize(page.getSize());
        pageResult.setPageTotal(page.getPages());
        pageResult.setList(resultList);

        return pageResult;
    }

    /**
     * 文件删除
     *
     * @param fileIdList
     */
    @Override
    @Transactional
    public void delFile(List<String> fileIdList) {
        // 把这些文件的删除时间更新到数据库并且更新文件回收站状态
        for (String fileId : fileIdList) {
            FileInfo fileInfo = fileInfoMapper.selectById(fileId);
            fileInfo.setDelType(FileDelTypeEnums.DEL_HAND.getFlag());
            fileInfo.setDelFlag(FileDelFlagEnums.RECYCLE.getFlag());
            fileInfo.setRecoveryTime(new Date());
            fileInfoMapper.updateById(fileInfo);
        }
    }

    /**
     * 重命名文件
     *
     * @param renameFileDTO
     * @return
     */
    @Override
    @Transactional
    public void rename(RenameFileDTO renameFileDTO) {
        String fileId = renameFileDTO.getFileId();
        String fileName = renameFileDTO.getFileName();

        LambdaQueryWrapper<FileInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FileInfo::getFileId, fileId);

        FileInfo fileInfoUp = new FileInfo();
        fileInfoUp.setFileName(fileName);
        fileInfoMapper.update(fileInfoUp, wrapper);
    }

    /**
     * 创建文件下载路径并且缓存
     *
     * @param fileId
     */
    @Override
    public String createDownloadURL(String fileId) {
        FileInfo fileInfo = fileInfoMapper.selectById(fileId);
        String redisDownLoadKey = fileId + "DownLoadCODE";
        DownLoadCodeDTO dto = new DownLoadCodeDTO();
        dto.setFileName(fileInfo.getFileName());
        dto.setFilePath(fileInfo.getFilePath());
        redisUtils.setex(redisDownLoadKey, dto, 10);
        return redisDownLoadKey;
    }

    /**
     * 创建文件夹
     *
     * @param filePid
     * @param fileName
     * @param loginUserVO
     */
    @Override
    @Transactional
    public FileInfo newFoloder(String filePid, String fileName, LoginUserVO loginUserVO) {
        String userEmail = loginUserVO.getUserId();
        String CodeEmailPart = com.fy.utils.StringTools.getEmailPrefix(userEmail);
        String fileId = CodeEmailPart + "ADD" + UUID.randomUUID().toString().substring(0, 6);

        // 1. 检查同一目录下是否存在同名文件夹
        LambdaQueryWrapper<FileInfo> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(FileInfo::getFilePid, filePid)
                .eq(FileInfo::getFileName, fileName)
                .eq(FileInfo::getFolderType, FileFolderTypeEnums.FOLDER.getType())
                .eq(FileInfo::getFileType, FileTypeEnums.OTHERS.getType())
                .eq(FileInfo::getDelType, FileDelFlagEnums.USING.getFlag())
                .eq(FileInfo::getDelFlag, FileDelFlagEnums.USING.getFlag())
                .eq(FileInfo::getUserId, userMapper.selectUserIdByName(loginUserVO.getNickName()));

        if (fileInfoMapper.selectCount(checkWrapper) > 0) {
            throw new ConditionException("文件夹已存在");
        }

        // 2. 创建文件夹对象
        FileInfo folder = new FileInfo();

        // 3. 设置基本信息
        folder.setFileId(fileId); // 生成随机文件ID
        folder.setUserId(userMapper.selectUserIdByName(loginUserVO.getNickName()));
        folder.setFilePid(filePid);
        folder.setFileName(fileName);
        folder.setFolderType(FileFolderTypeEnums.FOLDER.getType());
        folder.setDelType(FileDelFlagEnums.USING.getFlag());
        folder.setDelFlag(FileDelFlagEnums.USING.getFlag());
        folder.setCreateTime(new Date());
        folder.setLastUpdateTime(new Date());
        folder.setStatus(FileStatusEnums.USING.getStatus());

        // 5. 保存到数据库
        fileInfoMapper.insert(folder);

        return folder;
    }

    /**
     * 获取文件夹信息
     *
     * @param fileIds
     * @return
     */
    @Override
    public List<FoloderVO> getFoloderInfo(String fileIds) {
        FoloderVO foloderVO;
        List<FoloderVO> foloderVOList = new ArrayList<>();

        String[] strList = fileIds.split("/");
        for (String fId : strList) {
            foloderVO = new FoloderVO(); // 创建新的 FoloderVO 对象

            FileInfo fileInfo = fileInfoMapper.selectById(fId);
            foloderVO.setFileId(fileInfo.getFileId());
            foloderVO.setFileName(fileInfo.getFileName());

            foloderVOList.add(foloderVO);
        }

        return foloderVOList;
    }

    /**
     * 获取文件夹
     *
     * @param filePid
     * @param currentFileIds
     * @return
     */
    @Override
    public List<FileInfo> loadAllFolder(LoginUserVO loginUserVO, String filePid, String currentFileIds) {
        int userId = userMapper.selectUserIdByName(loginUserVO.getNickName());

        // 创建查询条件
        LambdaQueryWrapper<FileInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FileInfo::getUserId, userId)
                .eq(FileInfo::getFolderType, FileFolderTypeEnums.FOLDER.getType());

        // 如果是首页(filePid=0)，获取所有顶级文件夹
        if ("0".equals(filePid)) {
            queryWrapper.eq(FileInfo::getFilePid, "0");
        } else {
            // 否则获取指定filePid下的所有文件夹
            queryWrapper.eq(FileInfo::getFilePid, filePid);
        }

        // 如果currentFileIds不为空，排除这些文件夹
        if (StringUtils.isNotBlank(currentFileIds)) {
            String[] fileIds = currentFileIds.split(",");
            queryWrapper.notIn(FileInfo::getFileId, Arrays.asList(fileIds));
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(FileInfo::getCreateTime);

        return fileInfoMapper.selectList(queryWrapper);
    }

    /**
     * 移动文件
     *
     * @param fileIds
     * @param filePid
     */
    @Transactional
    @Override
    public void changeFileFolder(String fileIds, String filePid) {
        // 获取要移动的文件的id存入数组
        String[] fileIdStr = fileIds.split(",");
        // 把这些文件的filePid更新为filePid
        for (String fileId : fileIdStr) {
            FileInfo fileInfo = fileInfoMapper.selectById(fileId);
            fileInfo.setFilePid(filePid);
            fileInfoMapper.updateById(fileInfo);
        }
    }

    /**
     * 获取文件路径
     *
     * @param fileId
     * @return
     */
    @Override
    public FileInfo getFilePath(String fileId) {
        return fileInfoMapper.selectById(fileId);
    }

    /**
     * 获取文件统计
     *
     * @param id
     * @return
     */
    @Override
    public FileStatisticsVO getFileStatistics(Integer id) {
        FileStatisticsVO statistics = new FileStatisticsVO();

        // 获取文件总数
        LambdaQueryWrapper<FileInfo> fileQuery = new LambdaQueryWrapper<>();
        fileQuery.eq(FileInfo::getUserId, id);
        statistics.setTotalFiles(fileInfoMapper.selectCount(fileQuery));

        // 获取今日上传数
        LambdaQueryWrapper<FileInfo> todayQuery = new LambdaQueryWrapper<>();
        todayQuery.eq(FileInfo::getUserId, id)
                .apply("DATE(create_time) = CURDATE()");
        statistics.setTodayUploads(fileInfoMapper.selectCount(todayQuery));

        // 获取总分享数
        LambdaQueryWrapper<FileShare> shareQuery = new LambdaQueryWrapper<>();
        shareQuery.eq(FileShare::getUserId, id);
        fileShareMapper.selectCount(shareQuery);
        statistics.setTotalShares(fileShareMapper.selectCount(shareQuery));

        // 获取用户积分
        User user = userMapper.selectById(id);
        statistics.setPoints(user.getPoint());

        return statistics;
    }
}
